/*
 	登录
 * */
define(['../../common/service'], function( http) {
	(function bindLoginEvent(){
		window.sessionStorage.clear();

		var reportTitle = window.localStorage.getItem('report-list-22');
		window.localStorage.clear();
		window.localStorage.setItem('report-list-22', reportTitle);

		//配置I18N
		var sl = window.localStorage.getItem('language') || 'zh-cn';
		I18N.setLanguage(sl);

		var loginArea = $('#login'),
			userName = $('#username'),
			password = $('#password');
		//清除缓存
		userName.val('');
		password.val('');
		//记住我
		try{
			if(localStorage.getItem('rememberMe')){
				var rememberMeObj = localStorage.getItem('rememberMe');
				rememberMeObj=JSON.parse(rememberMeObj);
				if(rememberMeObj.rememberMe){
					$("#remember-me").prop("checked", rememberMeObj.rememberMe);
					$('#username').val(rememberMeObj.username);
				}
			}
		}catch (e){
			console.error(e)
		}
		//登录用户名输入enter，光标自动移到登录密码
		userName.unbind('keydown');
		userName.keydown(function(e){
			if(e.keyCode == 13){
				e.preventDefault();
				if($.trim($(this).val()) != '')
					password.focus();
			}
		});
		//登录密码输入enter，自动触发登录
		password.unbind('keydown');
		password.keydown(function(e){
			if(e.keyCode == 13)
				loginArea.trigger('click');
		});

		//登录事件
		loginArea.unbind('click');
		$("#login").bind('click', function(){
			if($.trim(userName.val()) == ''){
				Kit.alert_info(I18N.getText('user','enterName'));
				return false;
			}
			if($.trim(password.val()) == ''){
				Kit.alert_info(I18N.getText('user','enterPassword'));
				return false;
			}
			var param = {
					"username": userName.val(),
					"password": password.val()
				};
			//获取用户信息
            var loadingArea = $('#login-area');
            Kit.loading.show(loadingArea);
            http.work('/logusers/login',param,'POST').then(function(res){
            	if(res.flag == 'success'){
            		var data = res.data;
					var userInfo = data.userInfo;
					localStorage.setItem('uName',userInfo.username);
					localStorage.setItem('language',userInfo.language);
					if($('#remember-me').is(':checked')){//记住我
						var rememberMeObj = {
							rememberMe:true,
							username:userInfo.username
						}
						localStorage.setItem('rememberMe',JSON.stringify(rememberMeObj));
					}else{
						localStorage.removeItem('rememberMe');
					}
					window.sessionStorage.clear();
					window.sessionStorage.setItem('timezone',userInfo.timezoneId);
					var _href = window.location.href;
					var _url = _href.split('gotoUrl=')[1];
					window.location.href = _url ? _url : "index.html";
				}
				else{
					Kit.alert2(res.msg);
				}
				Kit.loading.hide(loadingArea);
			});
		});
	})();
})
